##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations.  All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
#
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
#
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
#
#
# Disclaimer
#
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
__doc__='''Stored Procedure

$Id: SP.py,v 1.12 2002/12/21 20:29:06 matt Exp $'''
__version__='$Revision: 1.12 $'[11:-2]

import sys
from Globals import HTMLFile
from OFS.SimpleItem import SimpleItem
from Shared.DC.ZRDB.TM import Surrogate
from string import split
from AccessControl import getSecurityManager
import DCOracle2
from db import LobLocator, DB

import logging
logger = logging.getLogger('DCOracle2 - SP.py')

myname = split(__name__,".")[1]
if myname == "ZOracleDA":
    dbstring = "Z Oracle"
else:
    dbstring = myname


class Procedure(SimpleItem):

    manage_options=(
        {'label': 'Edit', 'action':'manage_procview'},
        {'label': 'Test', 'action':'manage_proctest'},
        # {'label': 'Design', 'action':'manage_tables'},
        ) + SimpleItem.manage_options

    __ac_permissions__ =  (
        ('Change %s Stored Procedures' % dbstring,
         ('manage_editZOracleStoredProcedure',)),
        ('Execute %s Stored Procedures' % dbstring,
         ('manage_testZOracleStoredProcedure',"")),
    )

    manage_procview=HTMLFile('dtml/procview',globals())
    manage_proctest=HTMLFile('dtml/proctest',globals())

    info=None

    _lobConvert = DB._lobConvert

    def __init__(self, id, title, connection, procname, acquire, check):
        self.id = id
        self.title = title
        self.connection = connection
        self.procname = procname
        self.acquire = acquire
        #self._v_proc = None
        #self._v_db = None

    def getconn(self):
        """ Return the ResourceManager
        """
        return getattr(self,self.connection)() # Get the resource manager

    def getproc(self):
        rm = self.getconn()
        c = rm.getcursor()                          # Get cursor
        #self._errors = 0
        if self.procname:
            try:
                p = c.findproc(self.procname)        # Get procedure
                #logger.debug('getproc - returning procedure: \'%s\'' % (self.procname))
                return rm, p
            except DCOracle2.DatabaseError, mess:
                logger.error('getproc - error: \'%s\'' % (mess))
                #self._errors = self._errors + 1
                #if self._errors > 3: raise
                raise
        return rm, None

    def description(self):
        return self.getproc()[1].__doc__

    def ZSPAcquireType(self):
        aq = getattr(self,"acquire","never")
        if aq not in ("never", "request", "always"): aq = 'never'

        return aq

    def ZSPListPackage(self, package):
        rm = self.getconn()
        cd = rm.collapsedesc(rm.describe(package))

        package = cd[1]
        desc = cd[3]

        results = []

        for (schema, name, type, subdesc) in desc:
            if type == 'procedure' or type == 'function':
                results.append(('%s.%s' % (package, name),type.upper()))

        return results

    def ZSPListProcs(self):
        results = []

        rm = self.getconn()

        objs = rm.objects()

        for (name, type) in objs:
            if type in ('PROCEDURE', 'FUNCTION'):
                results.append((name, type))
            elif type == 'PACKAGE':
                r = self.ZSPListPackage(name)
                for entry in r:
                    results.append(entry)

        results.sort()
        return results

    def __call__(self, *args, **kw):
        #logger.debug('__call__')
        if not getSecurityManager().checkPermission(
            'Execute %s Stored Procedures' % dbstring, self):
            # Ugh raising a string error
            raise 'Unauthorized', "You are not authorized to access this resource"

        aq = self.ZSPAcquireType()

        if aq != 'never':
            REQUEST = getattr(self,'REQUEST',None)
        else:
            REQUEST = None

        rm, proc = self.getproc()

        if REQUEST is not None:
            # Our own version of the magic apply; take arguments out of REQUEST
            argc = 0
            argl = len(args)
            _notfound = []
            arglist = proc.argList()
            for (name, type, mode) in arglist:
                if 'IN' in mode:
                    argc = argc + 1
                    try:
                        v = REQUEST.get(name, _notfound)
                    except AttributeError:
                        v = _notfound
                    if v is _notfound and aq == 'always':
                        v = getattr(self, name, _notfound)
                    # Take an arg if it isn't in the positional or kw list
                    if (argl < argc and v is not _notfound and
                        not kw.has_key(name)):
                            kw[name] = v   # Auto-import as kw arg

        #self._register()
        rm.registerRM()
        try:
            # Note, this does not do result promotion like the DA query will
            # which is probably bad.  OracleDates in particular look like
            # DateTimes but arent at all the same!
            results = apply(proc,args,kw)            
            return self._lobConvert(rm, results)
        except DCOracle2.DatabaseError:
            raise                          # Reraise error

    def invars(self):
        d = self.description()
        ins = []
        lines = split(d,'\n')
        if len(lines) > 1:
            for l in lines[1:]:
                words = split(l)
                if len(words) > 1 and words[1] == 'IN': ins.append(words[0])
        return ins

    def manage_editZOracleStoredProcedure(self, title, connection, procname,
        procname2, acquire, URL1, RESPONSE=None):
        """Edit the stored procedure"""
        self.title = title
        self.connection = connection
        self.procname = procname or procname2
        self.acquire = acquire
        self._v_proc = None
        RESPONSE.redirect(URL1 + "/manage_procview?manage_tabs_message=Stored%20Procedure%20Changed")

    def manage_testZOracleStoredProcedure(self, REQUEST):
        """Test the stored procedure"""
        v = apply(self,[],REQUEST.form)
        return v

    def get_arg_list(self):
        """ This method was necessary for migration script
            DCOracle2->SQLRelay. May be used for such purposes.
        """
        rm, proc = self.getproc()
        return proc.argList()

    def _p_resolveConflict(self,old,saved,new):
        """
        Merges two possible procedure states
        Accounts only for additions and deletions, not changes of order
        Prevents duplicate add or remove of same Item during conflict
        
        This method is currently unnecessary. This is here because
        original implementation used self._errors parameter
        that caused writes to ZODB
        """
        return new